package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Slf4j
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加搜索记录
     *
     * @param keyWord
     */
    @Override
    @Async
    public void insert(String keyWord) {
        if (StringUtils.isEmpty(keyWord)) {
            return;
        }
        Integer userId = AppThreadLocalUtil.getUser();
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        Optional<ApUserSearch> first = apUserSearches.stream().filter(apUserSearch -> apUserSearch.getKeyword().equals(keyWord)).findFirst();
        if (first.isPresent()) {
            ApUserSearch apUserSearch = first.get();
            log.info("搜索记录:{} 已存在，更新时间", keyWord);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyWord);
        apUserSearch.setCreatedTime(new Date());
        if (apUserSearches.size() < 10) {
            log.info("搜索记录{} 不存在并且小于10条，新增", keyWord);
            mongoTemplate.save(apUserSearch);
        } else {
            log.info("搜索记录{} 不存在并且大于10条，删除最小时间记录，新增", keyWord);
            ApUserSearch min = apUserSearches.stream().min(Comparator.comparing(ApUserSearch::getCreatedTime)).get();
            Query queried = Query.query(Criteria.where("id").is(min.getId()));
            mongoTemplate.findAndReplace(queried, apUserSearch);
        }
    }

    /**
     * 查询搜索记录
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        Integer userId = AppThreadLocalUtil.getUser();
        if (userId == null) {
            return ResponseResult.okResult(null);
        }
        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 删除搜索记录
     *
     * @param map
     * @return
     */
    @Override
    public ResponseResult delUserSearch(Map<String, Object> map) {
        if (CollectionUtils.isEmpty(map) || map.get("id") == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        String id = map.get("id") + "";
        mongoTemplate.remove(Query.query(Criteria.where("id").is(id)), ApUserSearch.class);
        log.info("删除搜索记录:{}", id);
        return ResponseResult.okResult("删除成功");
    }
}
